package com.mashibing.juc.c_026_00_interview.A1B2C3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class T01_00_Question {
  public static void main(String[] args) {
    // 要求用线程顺序打印A1B2C3....Z26
    print();
  }

  public static void print() {
    String[] strArr = new String[] {"A", "B", "C", "D"};
    String[] intArr = new String[] {"1", "2", "3", "4"};
    ReentrantLock reentrantLock = new ReentrantLock();
    Condition condition1 = reentrantLock.newCondition();
    Condition condition2 = reentrantLock.newCondition();

    new Thread(
            () -> {
              try {
                reentrantLock.lock();
                for (String s : strArr) {
                  System.out.println(s);

                  condition2.signal();
                  condition1.await();
                }
                condition2.signal();
              } catch (InterruptedException e) {
                e.printStackTrace();
              } finally {
                reentrantLock.unlock();
              }
            })
        .start();
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    new Thread(
            () -> {
              try {
                reentrantLock.lock();
                for (String s : intArr) {
                  System.out.println(s);
                  condition1.signal();
                  condition2.await();
                }
              } catch (InterruptedException e) {
                e.printStackTrace();
              } finally {
                reentrantLock.unlock();
              }
            })
        .start();
  }
}
